/*================================================================
*   Copyright (C) 2024 baichao All rights reserved.
*
*   文件名称：main.c
*   创 建 者：baichao
*   创建日期：2024年04月10日
*   描    述：
*
================================================================*/

#include <stdio.h>

struct ListNode {
  int val;
  struct ListNode *next;
};

struct ListNode *mergeTwoLists(struct ListNode *list1, struct ListNode *list2) {
  if (list1 == NULL) {
    return list2;
  }

  if (list2 == NULL) {
    return list1;
  }

  struct ListNode *mergedList = NULL, *currMergedNode = NULL;
  if (list1->val <= list2->val) {
    mergedList = list1;
    list1 = list1->next;
  } else {
    mergedList = list2;
    list2 = list2->next;
  }
  currMergedNode = mergedList;

  while (list1 != NULL || list2 != NULL) {
    if (list1 == NULL) {
      currMergedNode->next = list2;
      break;
    } else if (list2 == NULL) {
      currMergedNode->next = list1;
      break;
    }

    if (list1->val <= list2->val) {
      currMergedNode->next = list1;
      list1 = list1->next;
    } else {
      currMergedNode->next = list2;
      list2 = list2->next;
    }
    currMergedNode = currMergedNode->next;
  }

  return mergedList;
}

int main() {
  struct ListNode *currNode = NULL;
  struct ListNode *listA = (struct ListNode *)malloc(sizeof(struct ListNode));

  listA->val = 1;
  listA->next = (struct ListNode *)malloc(sizeof(struct ListNode));
  currNode = listA->next;

  currNode->val = 2;
  currNode->next = (struct ListNode *)malloc(sizeof(struct ListNode));
  currNode = currNode->next;

  currNode->val = 4;
  currNode->next = NULL;

  currNode = NULL;
  struct ListNode *listB = (struct ListNode *)malloc(sizeof(struct ListNode));

  listB->val = 1;
  listB->next = (struct ListNode *)malloc(sizeof(struct ListNode));
  currNode = listB->next;

  currNode->val = 3;
  currNode->next = (struct ListNode *)malloc(sizeof(struct ListNode));
  currNode = currNode->next;

  currNode->val = 4;
  currNode->next = NULL;

  struct ListNode *afterList = mergeTwoLists(listA, listB);

  return 0;
}
